/*
 * 
 */
package es.drOsu.game;

import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.graphics.drawable.Drawable;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Toast;
import es.drOsu.common.Constants;
import es.drOsu.common.Tools;

// TODO: Auto-generated Javadoc
/**
 * The Class Orientation clase de practicas para el bonus de la brujula.
 */
public class Orientation extends Activity implements SensorEventListener{

	/** The sel x coordenada x donde se empieza a pintar la brujula. */
	private float selX = 0;
	
	/** The sel y coordenada y donde se empieza a pintar la brujula. */
	private float selY = 0;
	
	/** The stop x coordenada x donde se finaliza el pintado de las lineas de la brujula. */
	private float stopX = 0;
	
	/** The stop y coordenada y donde se finaliza el pintado de las lineas de la brujula. */
	private float  stopY = 0;
	
	/** The degrees grados de inclinacion de la linea base de la brujula. */
	private float degrees = (float) Math.random()*360;
	
	/** The m orientation values guarda los valores recogidos de los acelerometros necesarios para el pintado de la imagen de la brujula. */
	private float[] mOrientationValues = {200,200,200};
	
	/** The m magnetic values guarda los valores recogidos del acelerometro magnetico. */
	private float[] mMagneticValues;
	
	/** The m accelerometer values guarda los valores recogidos del acelerometro. */
	private float[] mAccelerometerValues;

	/** The TAG para depuracion en el LogCat. */
	private final String TAG = "Orientation";
	
	/** The m sensor manager guarda el manejador de los sensores de los acelerometros. */
	private SensorManager mSensorManager;
	
	/** The sensor list guarda un listado con todos los acelerometros de los que dispone el dispositivo. */
	private List<Sensor> sensorList;
	
	/** The orientationview vista donde se dibuja todos los elementos del bonus de la brujula. */
	private View orientationview;
	
	/** The compass guarda la imagen de la brujula. */
	private Drawable compass = null;
	
	/* (non-Javadoc)
	 * @see android.app.Activity#onCreate(android.os.Bundle)
	 */
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
	    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
	    orientationview = new Orientationview(this);
		setContentView(orientationview);
		mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
		
	}

		

	
	/* (non-Javadoc)
	 * @see android.app.Activity#onResume()
	 */
	@Override
	protected void onResume(){
		super.onResume();
    	sensorList = mSensorManager.getSensorList(Sensor.TYPE_ALL);
    	for (Sensor sensor : sensorList)
    		mSensorManager.registerListener(this, sensor,SensorManager.SENSOR_DELAY_NORMAL);
    }
    
    /* (non-Javadoc)
     * @see android.app.Activity#onPause()
     */
    @Override
	protected void onPause(){
    	super.onPause();
    	//Stop updates to save power while app paused
    	mSensorManager.unregisterListener(this);
    }
    
    /**
     * The Class Orientationview clase encargada de pintar todos los elementos del bonus de la brujula.
     */
    public class Orientationview extends View{
    	
	    /** The context contexto de la activdad. */
	    private Context context;
    	
	    /** The firsttime contra si es el primer pintado del bonus. */
	    private boolean firsttime = true;

		/**
		 * Instantiates a new orientationview crecion o instanciacion de la vista.
		 *
		 * @param context the context contexto de la actividad
		 */
		public Orientationview(Context context) {
    		super(context);
    		this.context = context;
    	}

    	/* (non-Javadoc)
	     * @see android.view.View#onDraw(android.graphics.Canvas)
	     */
	    @Override
    	protected void onDraw(Canvas canvas) {
    		
			// TODO Auto-generated method stub
    		if(firsttime){
    			compass = Tools.resizeImage(context, R.drawable.compass, getHeight(), getHeight(),true,270);
    			firsttime=false;
    		}
    		selX = orientationview.getWidth()/2;
    		stopX = selX;
    		selY = orientationview.getHeight()/2;
    		stopY = selY;
    		//Log.d(TAG, "selX: " + selX + " selY: " + selY);
    		Paint white = new Paint();
    		white.setColor(getResources().getColor(R.color.white));
    		canvas.drawRect(0, 0, getWidth(), getHeight(), white);
    		compass=Tools.resizeImage(context, R.drawable.compass, getHeight(), getHeight(), true, (int) (90-mOrientationValues[0]));//el 90 es para que indique el norte
    		//Log.d(TAG, "grados: "+(360-mOrientationValues[0]));
    		compass.setBounds((int)selX - compass.getIntrinsicWidth()/2, (int)selY - compass.getIntrinsicHeight()/2,(int) selX+compass.getIntrinsicWidth()/2, (int) selY+compass.getIntrinsicHeight()/2);
            compass.draw(canvas);
    		Paint selected = new Paint();
    		selected.setColor(getResources().getColor(R.color.black));
    		selected.setStyle(Style.STROKE);
    		selected.setStrokeWidth(3);
    		
    		Paint degreesPaint = new Paint();
    		degreesPaint.setColor(getResources().getColor(R.color.red));
    		degreesPaint.setStyle(Style.STROKE);
    		degreesPaint.setStrokeWidth(3);
    		//Restar 360 es para que vaya en el sentido de las agujas del reloj
    		canvas.drawLine(selX, selY, (stopX + (Constants.maxLengthLine*(float)Math.cos(Math.toRadians(360-mOrientationValues[0])))) , (stopY +(Constants.maxLengthLine*(float)Math.sin(Math.toRadians(360-mOrientationValues[0])))), selected);
    		canvas.drawLine(selX, selY, (stopX + (Constants.maxLengthLine*(float)Math.cos(Math.toRadians(360-degrees)))) , (stopY +(Constants.maxLengthLine*(float)Math.sin(Math.toRadians(360-degrees)))), degreesPaint);
    		
    		if ((degrees-3) <= Math.abs(mOrientationValues[0]) && (degrees+3) >= Math.abs(mOrientationValues[0])){
    			Toast.makeText(getBaseContext(), "gotcha", Toast.LENGTH_SHORT).show();
    			degrees = (float)Math.random()*360;
    		}
    		//Log.d(TAG,  "stopX: " + (stopX + (100*(float)Math.cos(mOrientationValues[0]))) +" stopY: " + (stopY +(100*(float)Math.sin(mOrientationValues[0])))+" mOrientation[0]: "+ mOrientationValues[0]+" mOrientation[1]: "+ mOrientationValues[1]+" mOrientation[2]: "+ mOrientationValues[2]);
    		//Log.d(TAG, "cos: " + (float)Math.cos(Math.toRadians(mOrientationValues[0])) + " sen: "+ (float)Math.sin(Math.toRadians(mOrientationValues[0])) + " mOrientation[0]: "+ mOrientationValues[0]);
    	}
    }
	
	/* (non-Javadoc)
	 * @see android.hardware.SensorEventListener#onAccuracyChanged(android.hardware.Sensor, int)
	 */
	@Override
	public void onAccuracyChanged(Sensor arg0, int arg1) {
		// TODO Auto-generated method stub
		
	}

	/* (non-Javadoc)
	 * @see android.hardware.SensorEventListener#onSensorChanged(android.hardware.SensorEvent)
	 */
	@Override
	public void onSensorChanged(SensorEvent event) {
		//Log.d(TAG, "entra en sensorEvent");
          /* switch(event.sensor.getType()) {
            case Sensor.TYPE_ORIENTATION:
                    mOrientationValues[0] = event.values[0];
                    mOrientationValues[1] = event.values[1];
                    mOrientationValues[2] = event.values[2];
                    //Log.d(TAG, "mOrientation tiene en onsensorchanged:" + mOrientationValues[0] + "-" + mOrientationValues[1]);
                    
                    orientationview.invalidate();
                break;
            }*/
		switch (event.sensor.getType()) {
	      case Sensor.TYPE_MAGNETIC_FIELD:
	        mMagneticValues = event.values.clone();
	        break;
	      case Sensor.TYPE_ACCELEROMETER:
	        mAccelerometerValues = event.values.clone();
	        break;
	      }

	      if (mMagneticValues != null && mAccelerometerValues != null) {
	        float[] R = new float[9];//corrdenadas que le metas en los valores de aceleracion y magnetismo 3x3 = 9
	        SensorManager.getRotationMatrix(R, null, mAccelerometerValues, mMagneticValues);
	        float[] orientation = new float[3];
	        SensorManager.getOrientation(R, orientation);
	        //Log.d(TAG, "grados: "+Math.toDegrees(orientation[0]));
	        mOrientationValues[0]=(float) Math.toDegrees(orientation[0]);
	        if(mOrientationValues[0]<0){
	        	mOrientationValues[0]+=360;
	        }
	        orientationview.invalidate();
	      }
	}
}
